package com.rou.im.framework.core.util;

import com.google.protobuf.Descriptors;
import com.google.protobuf.DynamicMessage;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2020-04-30 21:27
 */

public class ConvertUtil {

    //将一个字符串中的首字母转换成大写，其它的全部转换成小写
    public static String firstToUpperCase(String str) {
        String first = str.substring(0, 1);
        String after = str.substring(1); //substring(1),获取索引位置1后面所有剩余的字符串
        first = first.toUpperCase();
        after = after.toLowerCase();
        return first + after;
    }

    public static <T> T byteArrayToVO(byte[] data, Class<T> clz,Descriptors.Descriptor descriptor) throws Exception {
        DynamicMessage dynamicMessage = DynamicMessage.parseFrom(descriptor, data);
        Map<String, Object> maps = new HashMap<>();
        Map<Descriptors.FieldDescriptor, Object> allFields = dynamicMessage.getAllFields();
        for (Map.Entry<Descriptors.FieldDescriptor, Object> entry : allFields.entrySet()) {
            Descriptors.FieldDescriptor key = entry.getKey();
            maps.put(key.getJsonName(), entry.getValue());
        }
        T t = clz.newInstance();

        Field[] fields = clz.getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }
            field.setAccessible(true);
            field.set(t, maps.get(field.getName()));
        }

        // BeanUtils.populate(t, maps);
        return t;
    }


}
